package com.imflea.zero.service.meeting.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.imflea.zero.exception.BizException;
import com.imflea.zero.exception.MallServiceException;
import com.imflea.zero.model.dao.meeting.MeetingOrderInfoItemMapper;
import com.imflea.zero.model.entity.meeting.MeetingOrderInfo;
import com.imflea.zero.model.entity.meeting.MeetingOrderInfoItem;
import com.imflea.zero.model.entity.meeting.MeetingRoom;
import com.imflea.zero.model.entity.meeting.MeetingShop;
import com.imflea.zero.model.entity.meeting.dto.MeetingOrderInfoItemDto;
import com.imflea.zero.model.entity.meeting.dto.MeetingRoomDayTimeDto;
import com.imflea.zero.model.entity.meeting.dto.MeetingRoomTimeCheckDto;
import com.imflea.zero.model.entity.meeting.vo.DateTime4ItemStatusVO;
import com.imflea.zero.model.entity.meeting.vo.DateTime4ItemVO;
import com.imflea.zero.service.meeting.IMeetingOrderInfoItemService;
import com.imflea.zero.service.meeting.IMeetingRoomService;
import com.imflea.zero.service.meeting.IMeetingShopService;
import com.imflea.zero.util.base.CommonUtils;
import com.imflea.zero.utils.SessionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 空间订单表-分项表 服务实现类
 * </p>
 *
 * @author zzz
 * @since 2024-03-03
 */
@Service
public class MeetingOrderInfoItemServiceImpl extends ServiceImpl<MeetingOrderInfoItemMapper, MeetingOrderInfoItem> implements IMeetingOrderInfoItemService {
    @Autowired
    @Lazy
    private IMeetingShopService meetingShopService;
    @Autowired
    @Lazy
    private IMeetingRoomService meetingRoomService;


    @Override
    public MeetingOrderInfoItem saveOrUpdateMeetingOrderInfoItem(MeetingOrderInfoItem entity) {
        if (CommonUtils.isNull(entity.getId())) {
            entity.setId(CommonUtils.generateRandomString());
        }
        entity.setTenantId(SessionUtils.getTenantId());
        boolean b = this.saveOrUpdate(entity);
        if (!b) {
            throw new BizException("订单操作失败");
        }
        return entity;
    }

    @Override
    public PageInfo<MeetingOrderInfoItem> queryPage(MeetingOrderInfoItemDto dto) {
        Integer pageIndex = dto.getPageNum();
        Integer pageSize = dto.getPageSize();
        String tenantId = SessionUtils.getTenantId();
        QueryWrapper<MeetingOrderInfoItem> queryWrapper = new QueryWrapper<>();
        if (!CommonUtils.isNull(tenantId)) {
            queryWrapper.eq("tenant_id", tenantId);
        }
        PageHelper.startPage(pageIndex, pageSize);
        List<MeetingOrderInfoItem> adoptInfos = this.list(queryWrapper);
        PageInfo<MeetingOrderInfoItem> pageResult = new PageInfo<>(adoptInfos);
        return pageResult;
    }

    @Override
    public List<DateTime4ItemStatusVO> getCanOrderTimeByDateByDate(MeetingRoomDayTimeDto dayTimeDto) {
        LocalDate theDay = dayTimeDto.getTheDay();
        String roomId = dayTimeDto.getRoomId();
        //判断门店是否正在营业
        //获取营业时间
        MeetingRoom room = meetingRoomService.getById(roomId);
        if (CommonUtils.isNull(room)) {
            throw new MallServiceException("未找到该办公空间，可能已关闭，请选择其他空间或会议室");
        }
        MeetingShop shop = meetingShopService.getById(room.getShopId());
        if (CommonUtils.isNull(shop)) {
            throw new MallServiceException("该办公空间门店已不存在，可能已经关闭，请选择其他空间或会议室");
        }
        if (!"0".equals(shop.getStatus())) {
            throw new MallServiceException("该门店未营业，请选择其他空间或会议室");
        }
        String startTime = room.getDayStartTime();
        String endTime = room.getDayEndTime();

        Integer startIndex = 1;
        Integer endIndex = 24;
        if (!CommonUtils.isNull(startTime) && !CommonUtils.isNull(endTime)) {
            startIndex = Integer.valueOf(startTime.substring(0, 2));
            endIndex = Integer.valueOf(endTime.substring(0, 2));
        }


        QueryWrapper<MeetingOrderInfoItem> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("the_day", theDay);
        queryWrapper.eq("room_id", roomId);
        queryWrapper.orderByAsc("the_time");
        List<MeetingOrderInfoItem> list = this.list(queryWrapper);
        List<DateTime4ItemStatusVO> times = new ArrayList<>();
        for (int i = 1; i <= 24; i++) {
            DateTime4ItemStatusVO everyTime = new DateTime4ItemStatusVO();
            if (i < 10) {
                everyTime.setTheTime("0" + i + ":00");
            } else {
                everyTime.setTheTime(i + ":00");
            }
            everyTime.setTheDay(theDay);
            everyTime.setUseState("0");
            if (i < startIndex || i > endIndex) {
                everyTime.setUseState("2");
            }
            if (CommonUtils.isNull(list)) {

            } else {
                for (MeetingOrderInfoItem item : list) {
                    if (everyTime.getTheDay().isEqual(item.getTheDay()) && everyTime.getTheTime().equals(item.getTheTime())) {
                        everyTime.setUseState("1");
                        break;
                    }
                }

            }

            times.add(everyTime);
        }


        return times;
    }

    @Override
    public void saveOrderItemByOrder(MeetingOrderInfo order) {
        String orderId = order.getId();
        String bizId = order.getBizId();
        LocalDateTime startTime = order.getStartTime();
        LocalDateTime endTime = order.getEndTime();
        List<DateTime4ItemVO> orderItems = this.getOrderItems(startTime, endTime);
        for (DateTime4ItemVO vo : orderItems) {
            MeetingOrderInfoItem item = new MeetingOrderInfoItem();
            item.setId(CommonUtils.generateRandomString());
            item.setTenantId(SessionUtils.getTenantId());
            item.setRoomId(bizId);
            item.setOrderId(orderId);
            item.setTheDay(vo.getTheDay());
            item.setTheTime(vo.getTheTime());
            if (!this.checkIsOrdered(item)) {
                this.saveOrUpdateMeetingOrderInfoItem(item);
            } else {
                throw new MallServiceException("选择的时间已被预定，请重新选择");
            }

        }


    }

    public Boolean checkIsOrdered(MeetingOrderInfoItem item) {
        LocalDate theDay = item.getTheDay();
        String theTime = item.getTheTime();
        String roomId = item.getRoomId();
        QueryWrapper<MeetingOrderInfoItem> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("the_day", theDay);
        queryWrapper.eq("the_time", theTime);
        queryWrapper.eq("room_id", roomId);
        List<MeetingOrderInfoItem> list = this.list(queryWrapper);
        if (CommonUtils.isNull(list)) {
            return false;
        } else {
            return true;
        }
    }

    @Override
    public Boolean removeByOrderId(String orderId) {
        QueryWrapper<MeetingOrderInfoItem> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_id", orderId);
        boolean remove = this.remove(queryWrapper);
        return remove;
    }

    @Override
    public Boolean check(MeetingRoomTimeCheckDto dayTimeDto) {
        LocalDateTime startTime = dayTimeDto.getStartTime();
        LocalDateTime endTime = dayTimeDto.getEndTime();
        String roomId = dayTimeDto.getRoomId();
        List<DateTime4ItemVO> orderItems = this.getOrderItems(startTime, endTime);
        for (DateTime4ItemVO vo : orderItems) {
            MeetingOrderInfoItem item = new MeetingOrderInfoItem();
            item.setId(CommonUtils.generateRandomString());
            item.setTenantId(SessionUtils.getTenantId());
            item.setRoomId(roomId);
            item.setOrderId(roomId);
            item.setTheDay(vo.getTheDay());
            item.setTheTime(vo.getTheTime());
            if (this.checkIsOrdered(item)) {
                return false;
            }

        }
        return true;
    }

    private List<DateTime4ItemVO> getOrderItems(LocalDateTime startTime, LocalDateTime endTime) {
        int startHour = startTime.getHour();
        int endHour = endTime.getHour();
        int firstFlag = 0;
        List<LocalDate> dates = new ArrayList<>();

        List<DateTime4ItemVO> items = new ArrayList<>();
        //这里是判断开始日期是否在结束日期之后或者=结束日期
        while (startTime.isBefore(endTime) || startTime.isEqual(endTime)) {
            dates.add(startTime.toLocalDate());
            boolean isSameDay = startTime.toLocalDate().isEqual(endTime.toLocalDate());
            int calHour = 24;
            if (isSameDay) {
                calHour = endHour;
            }
            int start = 0;
            if (firstFlag == 0) {
                start = startHour;
            }
            for (int i = start; i <= calHour; i++) {
                String theTime = i < 10 ? ("0" + i + ":00") : (i + ":00");
                LocalDate theDay = startTime.toLocalDate();
                System.out.println(startTime.toLocalDate() + ":" + theTime);

                DateTime4ItemVO item = new DateTime4ItemVO();
                item.setTheTime(theTime);
                item.setTheDay(theDay);
                items.add(item);

            }
            startTime = startTime.plusDays(1);
        }
        return items;
    }

}
